package com.tianqu.tms.www.finance.controller;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.WeChatMqApi;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferFeeInfoBo;
import com.tianqu.tms.entity.Attn;
import com.tianqu.tms.entity.IntegralRegister;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.www.finance.viewhelper.TransferFeeManagementViewHelper;

public class TransferFeeManagementInputResultController  extends TmsController {
	private Logger logger = Logger.getLogger(CarProxyRetreatTransAccInputController.class);

	public final static String RECHARGE_PUSHCONTENT = "${会员名称}的过户费帐号，于${当前系统时间}成功充值${处理金额}元，帐号余额为${剩余余额}元";
	public final static String RETURNPREMIUM_PUSHCONTENT = "${会员名称}的过户费帐号，于${当前系统时间}成功退费${处理金额}元，帐号余额为${剩余余额}元";
	public final static String MEMBER_NAME = "会员名称";
	public final static String SYSTEM_TIME = "当前系统时间";
	public final static String TRANSFER_PRICE = "处理金额";
	public final static String VIRTUAL_MARGIN = "剩余余额";
	public final static String SIGN = "\\$";
	public final static String BEFOREBRACE = "\\{";
	public final static String LATERBRACE = "\\}";
	
	
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();
		try {
			controller.begin();
			
			TransferFeeManagementViewHelper view = (TransferFeeManagementViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			//
			TmsUserProfile profile = uc.getUserProfile();
			//
			Member member = new Member();
			Attn attn = new Attn();
			member = member.getIntegralManagementInfo(view.getAccessCardNo());
			attn = attn.getIntegralInfo(view.getAccessCardNo());
			//
			int realMargin = 0;
			int virtualMargin = 0;
			String realName = "";
			//
			if(member!=null){
				realMargin = member.getRealMargin();
				virtualMargin = Integer.parseInt(member.getVirtualMargin());
				realName = member.getRealName();
			}else if(attn!=null){
				realMargin = attn.getRealMargin();
				virtualMargin = attn.getVirtualMargin();
				realName = attn.getAttnName();
			}
			
			int plusMinus = 0;
			int chargeType = 0;
			int transferPrice = 0;
			String pushContent = "";
			String updataTime = DateUtil.getCurrentTime();
			//
			if("2".equals(view.getType())){//退费
				if(realMargin < virtualMargin){				
					realMargin = 0;
				}else {
					realMargin = realMargin - virtualMargin;
				}
				transferPrice = virtualMargin;
				virtualMargin = 0;
				chargeType = 11;
				plusMinus = 2;
				pushContent = getPushContent(realName,updataTime,String.valueOf(transferPrice),String.valueOf(virtualMargin),2);
			}else if("1".equals(view.getType())){//充值
				int price = Integer.parseInt(view.getPrice()) * 1000;
				transferPrice = price;
				realMargin += price;
				virtualMargin += price;
				chargeType = 10;
				plusMinus = 1;
				pushContent = getPushContent(realName,updataTime,String.valueOf(transferPrice),String.valueOf(virtualMargin),1);
			}
			
			int memberType = 0;
			String memberId = "";
			//更新会员基本信息数据表（tms_member）/经办人基本信息数据表（tms_attn）
			if(member!=null && !"2".equals(member.getUserId())){
				memberType = 1;
				memberId = member.getMemId() +"";
				member.setAccessCardNo(view.getAccessCardNo());//会员卡卡号
				member.setVirtualMargin(String.valueOf(virtualMargin));//过户费余额
				member.setRealMargin(realMargin);//充值过户费金额
				member.setUpdateUserId(profile.getUniqueId());//更新用户
				member.setRecharge("1".equals(view.getType())?Integer.parseInt(view.getPrice()) * 1000:0);
				//更新会员基本信息数据表（tms_member）
				member.updateMarginInfoByAccessCardNo(member);
			}else if(attn!=null&& !"2".equals(attn.getUserId())){
				memberType = 2;
				memberId =attn.getAttnId();
				attn.setAccessCardNo(view.getAccessCardNo());//会员卡卡号
				attn.setVirtualMargin(virtualMargin);//过户费余额
				attn.setRealMargin(realMargin);//充值过户费金额
				attn.setUpdateUserId(profile.getUniqueId());//更新用户
				attn.setRecharge("1".equals(view.getType())?Integer.parseInt(view.getPrice()) * 1000:0);
				//更新经办人基本信息数据表（tms_attn）
				attn.updateMarginInfoByAccessCardNo(attn);
			}			
			
			String remark = view.getRemark();
			//插入 积分登记表（tms_integral_register）
			IntegralRegister register = new IntegralRegister();
			register.setMemberId(memberId);//会员编号
			register.setMemberType(memberType);//会员类型
			register.setChargeType(chargeType);//业务处理类型
			register.setTransferPrice(transferPrice);//处理金额
			register.setPlusMinus(plusMinus);//业务处理方式
			register.setRemark(remark);//备注
			register.setInsertUserId(profile.getUniqueId());//插入用户
			register.setSerial("");//车辆流水号
			register.setLicensePlate("");//车牌号码
			register.setIntegral(0);//处理积分数
			register.insertRegisterInfo(register);
			
			controller.commit();
			
			//【TMS_web】过户费充值/退费 =》【TMS_app】同步
			TransferFeeInfoBo transferFeeInfoBo = new TransferFeeInfoBo();
			
			transferFeeInfoBo.setMemberId(memberId);
			transferFeeInfoBo.setMemberType(memberType);
			transferFeeInfoBo.setChargeType(chargeType);
			transferFeeInfoBo.setTransferPrice(transferPrice);
			transferFeeInfoBo.setRemark(remark);
			transferFeeInfoBo.setPlusMinus(plusMinus);
			transferFeeInfoBo.setPushContent(pushContent);
			transferFeeInfoBo.setRecharge("1".equals(view.getType())?Integer.parseInt(view.getPrice()) * 1000:0);
			transferFeeInfoBo.setRechargeTime(DateUtil.getCurrentTime());
			WeChatMqApi.getInstance().call(transferFeeInfoBo);
			
		} catch (Exception e) {
			logger.error(e);
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}
	public String getPushContent(String realName,String systemTime,String transferPrice,String virtualMargin ,int type)
	throws TmsDaoException {
		String contentStr = "";
		if(type == 1){//充值业务推送信息
			contentStr = RECHARGE_PUSHCONTENT;
		} else if(type == 2){//退费业务推送信息		
			contentStr = RETURNPREMIUM_PUSHCONTENT;
		}
		contentStr = contentStr.replaceAll(SIGN, "").replaceAll(BEFOREBRACE, "").replaceAll(LATERBRACE, "");
	
	    contentStr = contentStr.replaceAll(MEMBER_NAME, realName).replaceAll(SYSTEM_TIME, systemTime)
	    .replaceAll(TRANSFER_PRICE, transferPrice).replaceAll(VIRTUAL_MARGIN, virtualMargin); 
		return contentStr;
	}
}
